<template>
	<div class="layout-padding" v-loading="printing">
		<div class="layout-padding-auto layout-padding-view" style="overflow: auto">
			<el-row v-show="showSearch" style="width: 100%; text-align: right">
				<div style="font-size: 18px; font-weight: 700">项目概览</div>
				<el-form :model="queryForm" ref="queryRef" :inline="true" style="width: 100%">
					<el-form-item label="项目名称" prop="name" style="width: 500px">
						<el-select v-model="queryForm.projectId" placeholder="请选择项目名称" @change="handleProjectChange">
							<el-option :key="index" :label="item.name" :value="item.id" v-for="(item, index) in projectData" />
						</el-select>
					</el-form-item>
				</el-form>
			</el-row>
			<div ref="captureRef">
				<el-row class="w-full">
					<project-info :project-info="projectSelected" :year="queryForm.year" :is-print="printing" :type="2"></project-info>
				</el-row>
				<el-row class="mt-5" style="width: 100%">
					<div style="font-size: 18px; font-weight: 700; width: 40%">超支/节约分析</div>
					<!-- <el-form v-if="!printing" :model="queryForm1" ref="queryRef" :inline="true" style="width: 60%; text-align: right">
						<el-form-item label="年份" prop="name">
							<el-select v-model="queryForm1.year" placeholder="请选择年份" @change="handleMonthDataChange" clearable>
								<el-option :key="index" :label="item" :value="item" v-for="(item, index) in yearData" />
							</el-select>
						</el-form-item>
					</el-form>
					<div v-if="printing" style="width: 60%; font-size: 16px; text-align: right">
						{{ queryForm1.year + '年' }}
					</div> -->
				</el-row>
				<el-row>
					<el-card class="relative w-full mt-5">
						<echart-bar :type="1" :data-list="monthAnalysisData" :project-id="queryForm.projectId"></echart-bar>
					</el-card>
				</el-row>
				<el-row class="mt-5" style="width: 100%">
					<div style="font-size: 18px; font-weight: 700; width: 40%">成本项分析</div>
					<el-form v-if="!printing" :model="queryForm1" ref="queryRef" :inline="true" style="width: 60%; text-align: right">
						<el-form-item label="月份" prop="name">
							<el-select v-model="queryForm2.yearMonth" placeholder="请选择年月" @change="handleCostTypeDataChange" clearable>
								<el-option :key="index" :label="item.yearMonth" :value="item.yearMonth" v-for="(item, index) in monthAnalysisData" />
							</el-select>
						</el-form-item>
					</el-form>
					<div v-if="printing" style="width: 60%; font-size: 16px; text-align: right">
						{{ queryForm2.yearMonth }}
					</div>
				</el-row>
				<el-row>
					<el-card class="relative w-full mt-5">
						<echart-bar :type="2" :data-list="costTypeAnalysisData" :project-name="projectSelected.name"></echart-bar>
					</el-card>
				</el-row>
			</div>

			<el-row>
				<div class="mb8" style="width: 100%; text-align: right">
					<el-button type="primary" class="m-10" @click="handlePrint">打印</el-button>
				</div>
			</el-row>
		</div>
		<!-- 隐藏的打印容器 -->
		<div id="printContainer" class="only-print">
			<img :src="imageUrl" class="print-image" />
		</div>
	</div>
</template>

<script setup lang="ts" name="internalOverviewAnalysis">
import { Session } from '/@/utils/storage';
import VChart from 'vue-echarts';
import { use } from 'echarts/core';
import { BarChart, CustomChart } from 'echarts/charts';
import { TooltipComponent, LegendComponent, ToolboxComponent, GridComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import html2canvas from 'html2canvas';
import printJS from 'print-js';
use([TooltipComponent, LegendComponent, CanvasRenderer, ToolboxComponent, GridComponent, BarChart, CustomChart]);
import {
	getOverviewData as overviewAnalysis,
	getMonthProjectData as monthProjectAnalysis,
	getCostTypeProjectData as costTypeProjectAnalysis,
} from '/@/api/internal/cost/intProjectAnalysis';
// 引入组件
const ProjectInfo = defineAsyncComponent(() => import('./components/projectInfo.vue'));
const echartBar = defineAsyncComponent(() => import('./components/echart-bar.vue'));

const showSearch = ref(true);
const printing = ref(false); // 表格遮罩层

const getAllYears = (startYear: number, endYear: number) => {
	const years: number[] = [];
	for (let year = startYear; year <= endYear; year++) {
		years.push(year);
	}
	return years;
};

// 定义变量内容=
const projectData = ref<any[]>([]); // 项目列表
const projectSelected = ref({});
const monthAnalysisData = ref([]);
const costTypeAnalysisData = ref([]);

// 查询参数
const queryForm = reactive({
	projectId: '',
	// year: new Date().getFullYear(),
});
const queryForm1 = reactive({
	projectId: '',
	// year: new Date().getFullYear(),
});
const queryForm2 = reactive({
	projectId: '',
	yearMonth: '',
	// year: new Date().getFullYear(),
	// month: new Date().getMonth() + 1,
});

const getMonthProjectData = async () => {
	queryForm1.projectId = queryForm.projectId;
	monthProjectAnalysis(queryForm1).then((res) => {
		monthAnalysisData.value = res.data;
	});
};

const getCostTypeProjectData = async () => {
	queryForm2.projectId = queryForm.projectId;
	costTypeProjectAnalysis(queryForm2).then((res) => {
		costTypeAnalysisData.value = res.data;
	});
};

// 获取成本项分析数据
const getDataList = async () => {
	overviewAnalysis(queryForm).then((res) => {
		projectData.value = res.data;
		if (!projectSelected.value || Object.keys(projectSelected.value).length == 0) {
			if (!queryForm.projectId || queryForm.projectId == '') {
				projectSelected.value = projectData.value[0];
				queryForm.projectId = projectData.value[0]?.id;
			} else {
				projectSelected.value = projectData.value.filter((item) => item.id == queryForm.projectId)[0];
			}
			getMonthProjectData();
			getCostTypeProjectData();
		}
	});
};

getDataList();

// 元素引用
const captureRef = ref<HTMLElement | null>(null);
const imageUrl = ref<string>('');

const generatePrintImage = async () => {
	if (!captureRef.value) return;

	try {
		// 配置选项（可选）
		const options: html2canvas.Options = {
			scale: 4, // 缩放比例
			useCORS: true, // 允许跨域图片
			logging: true, // 调试日志
			backgroundColor: '#FFFFFF',
		};

		// 生成 canvas
		const canvas = await html2canvas(captureRef.value, options);

		// 转换为图片 URL
		const url = canvas.toDataURL('image/png');
		imageUrl.value = url;
	} catch (error) {
		console.error('截图失败:', error);
	}
};

const handleProjectChange = () => {
	projectSelected.value = projectData.value.filter((item) => item.id == queryForm.projectId)[0];
	getMonthProjectData();
	getCostTypeProjectData();
};

const handleCostTypeDataChange = () => {
	getCostTypeProjectData();
};
const handlePrint = () => {
	printing.value = true;
	nextTick(() => {
		generatePrintImage();
		setTimeout(() => {
			printing.value = false;
			printJS({
				printable: [imageUrl.value], // 提取 URL 数组
				type: 'image',
				header: '',
				style: '@media print { body { margin: 0; } #printSection { margin-top: 0; } img { max-width: 100%; page-break-inside: avoid; } }', // 内联CSS样式
				imageStyle: 'width: 100%; margin: 10px auto; page-break-after: always;', // 分页关键
			});
		}, 5000);
	});
};

// 页面加载时
onMounted(() => {
	queryForm.projectId = Session.get('projectId');
	Session.remove('projectId');
});
</script>
<style scoped>
/* 隐藏打印容器的优化方案 */
.only-print {
	display: none;
}

/* 打印时的图片样式 */
@media print {
	.print-image {
		width: 100% !important;
		height: auto !important;
		page-break-after: always; /* 分页控制（可选） */
	}
	.only-print {
		display: block !important; /* 显示仅在打印时可见的内容 */
	}
	@page {
		margin: 10px; /* 去除页边距 */
	}
}
</style>
